package com.yinhai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yinhai.domain.LoginUser;
import com.yinhai.mapper.MenuMapper;
import com.yinhai.mapper.UserMapper;
import com.yinhai.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author : chengxd
 * @create 2024/2/7 11:22
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    /**
     * 准备重写获取用户信息的方法
     * @param s
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        QueryWrapper wrapper = new QueryWrapper<User>().eq("user_name",s);
        User user = userMapper.selectOne(wrapper);

        if(Objects.isNull(user)){
            throw new UsernameNotFoundException("用户名或密码错误！");
        }

        // 据用户查询权限信息 添加到LoginUser中（目前先不讲，后面讲权限部分会补充）
        // 调用mapper查询对应的权限
        List<String> auth = menuMapper.selectPermsByUserId(user.getId());

        return new LoginUser(user,auth);
    }
}
